import {Injectable} from "@angular/core";
import {ToastController} from "ionic-angular";
import {Http, Headers} from "@angular/http";

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/timeout';
import {Camera, Device} from "ionic-native";
import 'rxjs/add/operator/map';

@Injectable()
export class services {
    private headers = new Headers({'Content-Type': 'application/json; charset=utf-8'});

    startTime: any;
    chgPwdStartTime: any;

    isReturn: boolean = false;
    collectedCount: any;

    status: number = 0; //0-初始，1-已获取订单，3-加钱成功，4-加钱失败
    loginId;
    items = [];
    perosonInfo;    //首页个人信息
    phone;
    activeModelText;
    personalDetail = {
        "companyAddressId": "",
        "companyAddressName": "",
        "companyId": "",
        "companyName": "",
        "id": "",
        "mobile": "",
        "name": "",
        "type": "0",
        "companyMemberLimit": "",
        "companyMobile": "",
    };
    areaList = [];
    infoData = {
        "id": '',
        "loginName": ''
    };
    homeProInfo;    //首页产品信息----------与后端人员沟通后此信息已经无用，可删除。
    productList02;    //根据经销商查询产品信息，即input框中的产品信息，多次用到，因此放到服务中；strogePage中productList相区别
    items2;         //根据产品查询发货渠道
    items3;         //根据产品查询收货渠道
    protectId;      //添加经销商时将产品ID放出来;
    protectId0;     //单个通过经销商查
    //添加经销商，但这个经销商已存在，对其添加多个产品时，放出产品ID
    productId2;

    cityData;   //城市JSON
    cityDataId;
    // cityName;   //转化之后的城市名（省 市 区）
    cityName: any[] = [];

    boxNo = '';     //箱码


    constructor(public http: Http, public toastCtrl: ToastController) {
    }

    /**
     * 错误回调
     * @param error
     * @returns {Promise<never>}
     */
    private handleError(error: any): Promise<any> {
        return Promise.reject(error.message || error);
    }

    /**
     * post请求
     * @param url
     * @param param
     * @returns {Promise<TResult|T>}
     */
    postMethod(url: string, param: any): Promise<any> {
        return this.http
            .post(url, JSON.stringify(param), {headers: this.headers})
            .timeout(2000)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

    /**
     * get请求JSON数据
     * @param url
     * @param param
     * @returns {Promise<TResult|T>}
     */
    getData(url: string): Promise<any> {
        return this.http
            .get(url)
            .timeout(2000)
            .toPromise()
            .then(response => response.json())
            .catch(err => {
                return Promise.reject(err)
            })
    }

    /*
     * 根据公司地址id查找省市区
     *
     * */
    compareCode(param: any) {
        console.log("传入的城市id：", param);
        this.cityName = [];
        let arr = param.split(',');
        for (let key in this.cityData) {
            let code1 = arr[1];
            if (this.cityData[key].code == code1) {
                this.cityName.push(this.cityData[key].name);
                let code2 = arr[2];
                for (let k in this.cityData[key].children) {
                    if (this.cityData[key].children[k].code == code2) {
                        this.cityName.push(this.cityData[key].children[k].name);
                        let code3 = arr[3];
                        for (let kk in this.cityData[key].children[k].children) {
                            if (this.cityData[key].children[k].children[kk].code == code3) {
                                this.cityName.push(this.cityData[key].children[k].children[kk].name);
                            }
                        }
                    }
                }
            }
        }
        return this.cityName;
    }

    /**
     * 拍照或选择本地图片
     * @param getType
     * @returns {Promise<[TResult]|T>}
     */
    public getNativePic(getType = 'CAMERA'): Promise<any> {
        console.log("获取照片方法:", getType);
        let options = {
            quality: 85,
            sourceType: Camera.PictureSourceType[getType],
            destinationType: Camera.DestinationType.FILE_URI,
            allowEdit: false,
            encodingType: Camera.EncodingType.JPEG,
            saveToPhotoAlbum: false,
            targetWidth: screen.width,
            targetHeight: screen.height,
            correctOrientation: true
        };
        return Camera.getPicture(options)
            .then(imageData => {
                console.log("图片数据:", imageData);
                return imageData;
            })
            .catch(this.handleError);
    }

    /**
     * 吐丝方法
     * @param msg
     */
    toast(msg: string): void {
        let toast = this.toastCtrl.create({
            message: msg,
            duration: 3000,
            position: 'bottom',
            cssClass: 'myToast'
        });
        toast.present();
    }

}
